import requests
from config import DEEPSEEK_API_KEY

class DeepseekAPI:
    def __init__(self):
        self.api_key = DEEPSEEK_API_KEY
        self.base_url = "https://api.deepseek.com/v1"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def chat(self, message):
        """
        发送消息到DeepSeek API并获取回复
        """
        try:
            # 确保消息是字符串类型
            if not isinstance(message, str):
                message = str(message)

            endpoint = f"{self.base_url}/chat/completions"
            payload = {
                "model": "deepseek-chat",
                "messages": [
                    {"role": "user", "content": message}
                ],
                "temperature": 0.7
            }

            response = requests.post(
                endpoint,
                headers=self.headers,
                json=payload
            )

            if response.status_code == 200:
                return response.json()['choices'][0]['message']['content']
            else:
                return f"API调用失败，状态码：{response.status_code}"

        except Exception as e:
            return f"发生错误：{str(e)}" 